package com.yc.favorite.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.yc.favorite.entity.Favorite;
import com.yc.favorite.entity.Tag;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author ly
 * @since 2023-10-24
 */
public interface TagMapper extends BaseMapper<Tag> {

    @Insert("insert into tag values(default," +
            "#{tname},#{tcount})")
    @Options(useGeneratedKeys = true, keyColumn = "tid",
            keyProperty = "tid")
    int insert(Tag tag);

    @Select("select * from tag where tname = #{tname}")
    Tag selectByName(String tname);

    @Override
    @Update("update tag set tcount = #{tcount}, tname = #{tname} where tid = #{tid}")
    int updateById(Tag entity);

    @Select("select * from tag a " +
            "where exists( select *" +
            "                from tagfavorite b " +
            "                join favorite c on b.fid=c.fid" +
            "               where a.tid = b.tid" +
            "                 and c.uid = #{uid})")
    @Results(
            value = {
                    @Result(column = "tid", property = "tid", id = true),
                    @Result(column = "tid", property = "favorites",
                    many = @Many( select =
                            "com.yc.favorite.mapper.FavoriteMapper.selectByTid" ))
            }
    )
    List<Tag> selectAll(Integer uid);

    @Update("update tag set tcount = tcount + 1\n" +
            "where tid in (" +
            "      select tid from tagfavorite where fid=#{fid})"
    )
    int updateTcountByFid(int fid);
}
